//
//  WH_CycleImage.m
//  16-CycleImage(CollectionView)
//
//  Created by ParkourH on 16/8/4.
//  Copyright © 2016年 ParkourH. All rights reserved.
//

#import "WH_CycleImage.h"
#import "UIImageView+WebCache.h"
#define kCollectionViewCellReuse @"reuse"

@interface WH_CycleImage () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation WH_CycleImage

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark ------------  layout布局  -----------
- (void)layoutSubviews {

    [super layoutSubviews];
    _collectionView.frame = self.bounds;
    _flowLayout.itemSize = self.bounds.size;
    [_collectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    
    _pageControl.frame = CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 30);
}

#pragma mark ------------  init(VC代码)  -----------
- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self createSubViews];
    }
    return self;
}
#pragma mark ------------  init(SB/xib)  -----------
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self createSubViews];
    }
    return self;
}

#pragma mark ------------  createSubViews  -----------
- (void)createSubViews {

    [self createCollectionView];
    [self createPageControl];
    
        
    [self addTimer];

}

/** 添加定时器 */
- (void)addTimer {

    // 创建一个timer并添加到loop中
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

/** 定时器行为 */
- (void)timerAction {

    self.pageControl.currentPage = self.collectionView.contentOffset.x / self.bounds.size.width;
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    NSInteger nextItem = currentIndexPath.item + 1;
    
    if (nextItem == self.array.count - 2) {
        nextItem = 0;
    }
    if (self.array) {
        
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:0];
    
    
    
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    
}
#pragma mark ------------  removetimer  -----------
- (void)removeTimer {

    // 取消timer
    [_timer invalidate];
    _timer = nil;
}


/** 创建collectionView */
- (void)createCollectionView {
    
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    
    [self addSubview:_collectionView];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[WH_CycleImageCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
    
    _collectionView.pagingEnabled = YES;
    
    _collectionView.showsHorizontalScrollIndicator = NO;
}
/** 创建pageControl */
- (void)createPageControl {

    self.pageControl = [[UIPageControl alloc] init];
    [self addSubview:_pageControl];
    [self.pageControl addTarget:self action:@selector(pageAction) forControlEvents:UIControlEventValueChanged];
    
}
/** page方法 */
- (void)pageAction {

    [self timerAction];
}

#pragma mark ------------  数组的set方法  -----------
- (void)setArray:(NSMutableArray *)array {

    _array = array;
    
    
    NSString *firstImage = [_array firstObject];
    NSString *lastImage = [_array lastObject];
    [_array insertObject:lastImage atIndex:0];
    [_array addObject:firstImage];

    _pageControl.numberOfPages = _array.count - 2;
    
    [_collectionView reloadData];
}


#pragma mark ------------  DataSource  -----------
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _array.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    WH_CycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    
//    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.item]];
    NSURL *url = _array[indexPath.item];
    [cell.cycleImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"guanggao"]];
    
    if (self.dataSource != nil && [self.dataSource respondsToSelector:@selector(handleDataWithObject:cell:)]) {
    
        [self.dataSource handleDataWithObject:_array[indexPath.item] cell:cell];
    }
    
    return cell;
}

#pragma mark ------------  scrollView结束减速  -----------
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    // 直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
        
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x == _collectionView.bounds.size.width * (_array.count - 1)) {

        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        
    }
    
    self.pageControl.currentPage = self.collectionView.contentOffset.x / self.bounds.size.width - 1;
}

#pragma mark ------------  当用户拖拽时停止timer  -----------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark ------------  当用户停止拖拽时添加timer  -----------
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    [self addTimer];
}

@end


#pragma mark ------------  CustomCollectionViewCell  -----------

@implementation WH_CycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
        
        }
    return self;
}

@end


